﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DukeNUS.FacilitiesPlanning.FPSystem;
using DukeNUS.FacilitiesPlanning.FPSystem.Data;
using DukeNUS.FacilitiesPlanning.FPSystem.Helpers.Cryptography;
using DukeNUS.FacilitiesPlanning.FPSystem.Models;
using DukeNUS.FacilitiesPlanning.FPSystem.Models.Login;
using System.Diagnostics;
using System.Transactions;

namespace DukeNUS.FacilitiesPlanning.FPSystem.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(AccountCredential credential)
        {
            var encryptedPassword = Cryptographer.Encrypt(credential.Password);
            var response = new LoginResponse()
            {
                UserName = credential.UserName,
                Password = encryptedPassword
            };

            if (ModelState.IsValid)
            {
                if (Session[ApplicationSessionKeys.CurrentUser] != null)
                    response.Errors = new ErrorResponse[] { 
                        new ErrorResponse() {
                            Message =  ApplicationErrorMessage.GetErrorMessage(ApplicationErrorMessages.MultipleLoginAttempt)
                        }
                    };
                else
                {                  
                    using (DukeNUSDatabase db = new DukeNUSDatabase())
                    {
                        var query = (from users in db.Users
                                     where (users.UserName.Equals(credential.UserName) &&
                                            users.Password.Equals(encryptedPassword))
                                     select users).ToList();

                        if (!query.Any())
                            response.Errors = new ErrorResponse[] { 
                                new ErrorResponse() {
                                    Message =  ApplicationErrorMessage.GetErrorMessage(ApplicationErrorMessages.InvalidLogonCredentials)
                                }
                            };
                        else
                        {
                            Session.Clear();

                            var currentUser = query.First();

                            using (TransactionScope trans = new TransactionScope())
                            {
                                try
                                {
                                    db.LogActivities.Add(new LogActivity()
                                    {
                                        Action = ApplicationActions.Login,
                                        UserID = currentUser.UserID
                                    });

                                    db.SaveChanges(); trans.Complete();

                                    Session[ApplicationSessionKeys.CurrentUser] = new ApplicationUser()
                                    {
                                        IsLoggedIn = true,
                                        User = currentUser
                                    };

                                    response.Successful = true;
                                }
                                catch (Exception ex)
                                {
                                    EventLog.WriteEntry(GetType().FullName, string.Format("Message: {0}\nStack Trace: {1}", ex.Message, ex.StackTrace), EventLogEntryType.Error);

                                    response.Errors = new ErrorResponse[] {
                                        new ErrorResponse() {
                                            Message = ex.Message,
                                            StackTrace = ex.StackTrace
                                        }
                                    };
                                }
                            }
                        }
                    }
                }
            }
            else response.Errors = new ErrorResponse[] { 
                    new ErrorResponse() {
                        Message =  ApplicationErrorMessage.GetErrorMessage(ApplicationErrorMessages.InvalidLogonCredentials)
                    }
                };

            return Json(response);
        }

    }
}
